<?php

namespace app\index\model;

use fast\Tree;
use think\Cache;
use think\Model;

class Nav extends Model
{
    public function getUrlAttr($value, $data) {
        return $value ? $value : ($data['type'] == 'page' ? '/show/'.$data['id'] : 'javascript:;');
    }

    public  function getNavList()
    {
        $lists = json_decode(Cache::get('nav_list'), true);
        if (!$lists) {
            $lists = $this->lists();
        }
        return $lists;
    }

    private function lists()
    {
        $lists = $this->where('onlineswitch', 1)->where('pid', 0)->order('weigh desc')->select();
        foreach ($lists as $key=>$val) {
            $val['children'] = $this->where('onlineswitch', 1)->where('pid', $val['id'])->order('weigh desc')->select();
        }
        Cache::set('nav_list', json_encode($lists), 0);
        return $lists;
    }

    public function child()
    {
        return $this->hasMany(NavList::class);
    }

    public static function getByPid($id)
    {
        return self::where('pid', $id)->where('onlineswitch', 1)->order('weigh desc')->select();
    }

    public static function getByName($name)
    {
        return self::where('name', $name)->find();
    }

}
